package cat

import (
	"errors"
	"net"
	"os"
	"strconv"
	"strings"

	conf "gitee.com/familydoc/plugin/config"
)

type Config struct {
	domain   string
	hostname string
	env      string
	ip       string
	ipHex    string

	httpServerPort      int
	httpServerAddresses []serverAddress

	serverAddress []serverAddress
}

var config = Config{
	domain:   defaultAppKey,
	hostname: defaultHostname,
	env:      defaultEnv,
	ip:       defaultIp,
	ipHex:    defaultIpHex,

	httpServerPort:      8080,
	httpServerAddresses: []serverAddress{},

	serverAddress: []serverAddress{},
}

func (config *Config) Init(domain string) (err error) {
	config.domain = domain

	defer func() {
		if err == nil {
			logger.Infof("Cat has been initialized successfully with appkey: %s", config.domain)
		} else {
			logger.Error("Failed to initialize cat.")
		}
	}()

	// TODO load env.

	var ip net.IP
	if ip, err = getLocalhostIp(); err != nil {
		config.ip = defaultIp
		config.ipHex = defaultIpHex
		logger.Warnf("Error while getting local ip, using default ip: %s", defaultIp)
	} else {
		config.ip = ip2String(ip)
		config.ipHex = ip2HexString(ip)
		logger.Infof("Local ip has been configured to %s", config.ip)
	}

	if config.hostname, err = os.Hostname(); err != nil {
		config.hostname = defaultHostname
		logger.Warnf("Error while getting hostname, using default hostname: %s", defaultHostname)
	} else {
		logger.Infof("Hostname has been configured to %s", config.hostname)
	}

	serverAddrs := conf.GetStringSlice("log.cat")
	if len(serverAddrs) == 0 {
		err = errors.New("error server address")
		logger.Warnf("Error server address, cat servers: null")
	}

	for _, serverAddr := range serverAddrs {
		server := strings.Split(serverAddr, ":")
		if len(server) != 2 {
			err = errors.New("error server address string")
			logger.Warnf("Error server address, cat servers: %s", serverAddr)
		}

		var port int
		if port, err = strconv.Atoi(server[1]); err != nil {
			err = errors.New("error server address port")
			logger.Warnf("Error server port, cat servers: %s", serverAddr)
		}

		config.httpServerAddresses = append(config.httpServerAddresses, serverAddress{
			host: server[0],
			port: port,
		})
	}

	logger.Infof("Server addresses: %s", config.httpServerAddresses)

	return
}
